import { APP_VER, UPLPAD_URL } from '@/env.js'
import { isH5, isH5Dev, isWx } from './is.js'
import { trim, getTime } from './utils.js'
import store from '@/store'
// #ifdef H5
import h5Copy from '@/plugins/junyi-h5-copy/index.js'
// #endif

export const checkLogin = () => {
  if (store.state.token) {
    return true
  } else {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return false
  }
}

/**
 * [cache 本地缓存 同步, ceche('key', null)-> 删除指定key的缓存, ceche('', null)-> 删除所有缓存 ]
 * @param  {string} key [本地缓存中指定的key]
 * @param  {''|null}   value   [本地缓存中指定的value, value=''是取值, value=null是清除]
 * @param  {int} exp [缓存的有效时间]
 */
export const cache = (key = '', value = '', exp = 0) => {
  var time = getTime()
  var obj = {}
  key = APP_VER + key
  if (value === '') {
    obj = uni.getStorageSync(key)
    if (!obj) {
      return null
    } else if (obj.exp === 0 || obj.exp > time) {
      return obj.value
    } else {
      uni.removeStorageSync(key)
      return null
    }
  } else if (value === null) {
    if (key === APP_VER)
      uni.clearStorageSync()
    else
      uni.removeStorageSync(key)
    return true
  } else {
    obj = {
      value: value,
      exp: exp > 0 ? time + exp : 0
    }
    uni.setStorageSync(key, obj)
    return true
  }
}

export const wxConfig = data => {
  jWeixin.config(data)
}

export const wxpay = (data = {}) => {
  return new Promise((resolve, reject) => {
    data.success = resolve
    data.fail = reject
    // #ifdef H5
    data.timestamp = data.timeStamp
    delete data.timeStamp
    jWeixin.chooseWXPay(data)
    // #endif
    // #ifndef H5
    uni.getProvider({
      service: 'payment',
      success: function(pro) {
        data.provider = pro.provider
        uni.requestPayment(data)
      }
    })
    // #endif
  })
}

export const chooseFile = (obj = {}) => {
  return new Promise((resolve, reject) => {
    obj.success = res => {
      let arr = []
      let index = 0
      let files = res.tempFilePaths
      let length = files.length

      function upload() {
        uni.uploadFile({
          url: UPLPAD_URL,
          filePath: files[index],
          name: 'file',
          header: { Authorization: 'Bearer ' + store.state.token },
          formData: {},
          success: res2 => {
            if (res2.statusCode === 200) {
              var data = JSON.parse(res2.data)
              data.status === 200 && arr.push(data.data)
            }
            index++
          },
          complete: () => {
            index < length ? upload() : resolve(arr)
          }
        })
      }
      upload()
    },
    obj.fail = reject
    uni.chooseFile(obj)
  })
}

export const chooseImage = (obj = {}) => {
  return new Promise((resolve, reject) => {
    obj.success = res => {
      let arr = []
      let index = 0
      let files = res.tempFilePaths
      let length = files.length

      function upload() {
        uni.uploadFile({
          url: UPLPAD_URL,
          filePath: files[index],
          name: 'file',
          header: { Authorization: 'Bearer ' + store.state.token },
          formData: {},
          success: res2 => {
            if (res2.statusCode === 200) {
              var data = JSON.parse(res2.data)
              data.status === 200 && arr.push(data.data)
            }
            index++
          },
          complete: () => {
            index < length ? upload() : resolve(arr)
          }
        })
      }
      upload()
    },
    obj.fail = reject
    uni.chooseImage(obj)
  })
}

// 预览图片
export const previewImage = (urls, current = 0) => {
  return new Promise((resolve, reject) => {
    if (typeof urls === 'string') urls = [urls]
    let obj = {
      current: current === 'string' && current ? current : urls[current],
      urls,
      success: resolve,
      fail: reject
    }
    if (isWx()) {
      jWeixin.previewImage(obj)
    } else {
      uni.previewImage(obj)
    }
  })
}

export const saveImage = url => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url,
      success: res => {
        if (res.statusCode !== 200) return reject
        else return uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: resolve,
          fail: reject
        })
      },
      fail: reject
    })
  })
}

export const getImageInfo = src => {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src,
      success: resolve,
      fail: reject
    })
  })
}

export const getLocation = (obj = {}) => {
  return new Promise((resolve, reject) => {
    obj.success = resolve
    obj.fail = reject
    if (isH5Dev()) {
      resolve({ latitude: 0, longitude: 0 })
    } else if (isWx()) {
      jWeixin.getLocation(obj)
    } else {
      uni.getLocation(obj)
    }
  })
}

export const openLocation = (obj = {}) => {
  return new Promise((resolve, reject) => {
    if (typeof obj.latitude === 'string') obj.latitude = Number(obj.latitude)
    if (typeof obj.longitude === 'string') obj.longitude = Number(obj.longitude)
    if (!obj.latitude) obj.latitude = 39.5427
    if (!obj.longitude) obj.longitude = 116.2317
    obj.success = resolve
    obj.fail = reject
    if (isWx()) {
      jWeixin.openLocation(obj)
    } else {
      uni.openLocation(obj)
    }
  })
}

export const getAppShareUrl = (url = '', append = {}) => {
  let pages = getCurrentPages()
  let currentPage = pages[pages.length - 1]
  let {
    route,
    options
  } = currentPage
  let param = {
    ...options,
    ...append
  }
  if (store.state.userInfo?.id) {
    param.fc = store.state.userInfo.id
  }
  let query = ''
  for (let i in param) {
    query += `&${i}=${param[i]}`
  }
  return `/${url || route}` + query.replace('&', '?')
}

export const getShareUrl = (link = '', append = {}) => {
  if (!link) link = window.location.href
  let [host] = link.split('#')
  let [path, query] = host.split('?')
  let params = {}
  if (query) {
    let arr = query.split('&')
    let filter = ['pid', 'code', 'state']
    for (var i = 0; i < arr.length; i++) {
      let pair = arr[i].split('=')
      let val = trim(pair[1], '/')
      if (val && filter.indexOf(pair[0]) === -1) {
        params[pair[0]] = val
      }
    }
  }
  if (store.state.userInfo?.id) params.fc = store.state.userInfo.id
  params = {
    ...params,
    ...append
  }
  if (JSON.stringify(params) === '{}') {
    return link.replace(`?${query}`, '')
  }
  let requery = JSON.stringify(params).replace(/["{}]/g, '').replace(/:/g, '=').replace(/,/g, '&')
  if (query) {
    return link.replace(query, requery)
  } else {
    let repath = ~host.indexOf('?') ? `${path}?` : path
    return link.replace(repath, `${path}?${requery}`)
  }
}

export const wxShare = (obj = {}, delay = 300) => {
  var { share_title, share_desc, share_logo } = store.state.config
  if (isH5()) {
    return new Promise((resolve, reject) => {
      obj.success = resolve
      obj.fail = reject
      obj.cancel = reject
      if (!obj.title) obj.title = share_title ?? ''
      if (!obj.desc) obj.desc = share_desc ?? ''
      if (!obj.imgUrl) obj.imgUrl = share_logo ?? ''
      obj.desc = obj.desc.length > 50 ? (obj.desc.substr(0, 50) + '...') : obj.desc
      return setTimeout(() => {
        return jWeixin.ready(function() {
          obj.link = getShareUrl(obj.link)
          jWeixin.onMenuShareAppMessage(obj) // 分享给朋友
          var line = JSON.parse(JSON.stringify(obj))
          line.title = `${line.title}\r\n${line.desc}`
          jWeixin.onMenuShareTimeline(line) // 分享给朋友圈
        })
      }, delay)
    })
  } else {
    let path = getAppShareUrl()
    return {
      title: obj.title ? obj.title : share_title,
      imageUrl: obj.imgUrl ? obj.imgUrl : share_logo,
      path: obj.link ? obj.link : path
    }
  }
}

export const scanQRCode = (obj = {}) => {
  return new Promise((resolve, reject) => {
    obj.success = resolve
    obj.fail = reject
    if (isH5Dev()) {
      resolve({ resultStr: 'SDDP202205310000001U0001', result: 'SDDP202205310000001U0001' })
    } else if (isWx()) {
      obj.needResult = obj?.needResult ?? 1
      obj.scanType = obj?.scanType ?? ['qrCode', 'barCode']
      jWeixin.scanQRCode(obj)
    } else {
      uni.scanCode(obj)
    }
  })
}

export const wxLogin = (obj = {}) => {
  return new Promise((resolve, reject) => {
    obj.provider = obj?.provider ?? 'weixin'
    obj.success = resolve
    obj.fail = reject
    uni.login(obj)
  })
}

export const wxUserProfile = (obj = {}) => {
  return new Promise((resolve, reject) => {
    if (obj.desc) obj.desc = '用于完善会员资料'
    obj.success = resolve
    obj.fail = reject
    uni.getUserProfile(obj)
  })
}

// 页面滚动到置顶位置
export const scrollTo = (val = 0) => {
  uni.pageScrollTo({
    scrollTop: val,
    duration: 100
  })
}

export const telCall = phone => {
  uni.makePhoneCall({ phoneNumber: phone })
}

export const copy = (str, msg) => {
  // #ifdef  H5
  // 仅H5剪切板
  const result = h5Copy(str)
  toast(result === false ? '不支持复制' : (msg || '复制成功'))
  // #endif

  // #ifndef  H5
  // 非H5剪切板
  uni.setClipboardData({
    data: str,
    success: function() {
      toast(msg || '复制成功')
    }
  })
  // #endif
}

export const toast = (obj = {}) => {
  if (typeof obj === 'string') {
    obj = { title: obj }
  }
  if (!obj?.icon) {
    obj.icon = 'none'
  }
  uni.showToast(obj)
}

export const showModal = (obj = {}) => {
  return new Promise((resolve, reject) => {
    obj.success = res => {
      if (res.confirm) resolve()
      else reject()
    }
    obj.fail = reject
    uni.showModal(obj)
  })
}

/**
 * opt  object | string
 * to_url object | string
 * 例:
 * this.Tips('/pages/test/test'); 跳转不提示
 * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
 * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
 * tab=1 一定时间后跳转至 table上
 * tab=2 一定时间后跳转至非 table上
 * tab=3 一定时间后返回上页面
 * tab=4 关闭所有页面跳转
 * tab=5 关闭当前页面跳转至非table上
 */
export const tips = (opt, to_url) => {
  if (typeof opt === 'string') {
    to_url = opt
    opt = {}
  }
  let title = opt.title || ''
  let icon = opt.icon || 'none'
  let endtime = opt.endtime || 1500
  let success = opt.success
  if (title) uni.showToast({
    title: title,
    icon: icon,
    duration: endtime,
    success
  })
  if (typeof to_url !== 'undefined') {
    if (typeof to_url === 'object') {
      let tab = to_url.tab || 1
      let url = to_url.url || ''
      switch (tab) {
        case 1:
          // 一定时间后跳转至 table
          setTimeout(function() {
            uni.switchTab({ url: url })
          }, endtime)
          break
        case 2:
          // 跳转至非table页面
          setTimeout(function() {
            uni.navigateTo({ url: url })
          }, endtime)
          break
        case 3:
          // 返回上页面
          setTimeout(function() {
            // #ifndef H5
            uni.navigateBack({
              delta: parseInt(url)
            })
            // #endif
            // #ifdef H5
            history.back()
            // #endif
          }, endtime)
          break
        case 4:
          // 关闭当前所有页面跳转至非table页面
          setTimeout(function() {
            uni.reLaunch({ url: url })
          }, endtime)
          break
        case 5:
          // 关闭当前页面跳转至非table页面
          setTimeout(function() {
            uni.redirectTo({ url: url })
          }, endtime)
          break
      }
    } else if (typeof to_url === 'function') {
      setTimeout(function() {
        to_url && to_url()
      }, endtime)
    } else {
      // 没有提示时跳转不延迟
      setTimeout(function() {
        uni.navigateTo({ url: to_url })
      }, title ? endtime : 0)
    }
  }
}

class Navigates {
  constructor(type) {
	  this.type = type || 'navigateTo'
  }
  isTabBar() {
    return ['switchTab', 'reLaunch'].includes(this.type)
  }
  navigate(path = '', query = {}) {
    let [url, search] = path.split('?')
    if (url[0] !== '/') {
      url = '/' + url
    }
    let tabBarPages = tabBar?.list.map(v => '/' + v.pagePath)
    if (!this.isTabBar() && tabBarPages.includes(url)) {
      this.type = 'switchTab'
    }
    if (!this.isTabBar()) {
      if (search) {
        let searchArr = search.split('&')
        for (let i in searchArr) {
          let [qk, qv] = searchArr[i].split('=')
          query[qk] = qv
        }
      }
      let queryStr = JSON.stringify(query)
      if (queryStr !== '{}') {
        url += '?' + queryStr.replace(/["{}]/g, '')
          .replace(/:/g, '=')
          .replace(/,/g, '&')
      }
    }
	  switch (this.type) {
	    case 'navigateTo':
	      uni.navigateTo({ url })
	      break
	    case 'redirectTo':
	      uni.redirectTo({ url })
	      break
	    case 'reLaunch':
	      uni.reLaunch({ url })
	      break
	    case 'switchTab':
	      uni.switchTab({ url })
	      break
	    case 'navigateBack':
	      uni.navigateBack({})
	      break
	    default:
	      warn('navigate Error')
	      break
	  }
  }
  /**
	 * uni.navigateTo
	 * @param url
	 * @param query
	 */
  push(url = '', query = {}) {
	  this.type = 'navigateTo'
	  this.navigate(url, query)
  }
	
  /**
	 * uni.redirectTo
	 * @param url
	 * @param query
	 */
  replace(url = '', query = {}) {
	  this.type = 'redirectTo'
	  this.navigate(url, query)
  }
	
  /**
	 * uni.reLaunch
	 * @param url
	 * @param query
	 */
  replaceAll(url = '', query = {}) {
	  this.type = 'reLaunch'
	  this.navigate(url, query)
  }
	
  /**
	 * uni.switchTab
	 * @param url
	 * @param query
	 */
  pushTab(url = '', query = {}) {
	  // 微信小程序端uni.switchTab拦截无效处理
	  /* #ifdef MP-WEIXIN */
	  if (!routerBeforeEach(url)) {
	    return
	  }
	  /* #endif */
	  this.type = 'switchTab'
	  this.navigate(url, query)
  }
	
  /**
	 * uni.navigateBack
	 * @param query
	 */
  back(query = {}) {
	  this.type = 'navigateBack'
	  this.navigate('', query)
  }
	
  /**
	 * 自动判断跳转页面 (navigateTo|switchTab)
	 * @param url
	 * @param query
	 */
  go(url = '', query = {}) {
	  const path = filterPath(url)
	  const routes = $store.state.app.routes
	  const route = routes?.get(path)
	  if (route?.meta?.tabBar) {
	    this.pushTab(url, query)
	    return
	  }
	  if (query?.replace) {
	    this.replace(url, query)
	    return
	  }
	  this.push(url, query)
  }
}

export const router = new Navigates() 
